package com.bk.cyxf.lf;

import jt.classic.system.ISystem;
import jt.classic.system.object.IObject;
import jt.classic.system.object.ObjectLCManager;
import jt.classic.system.object.ObjectManager;
import jt.classic.system.purview.PurviewManager;
import jt.classic.system.role.IRole;
import jt.classic.system.role.RoleManager;
import jt.classic.system.user.IUser;
import org.limp.basework.MachiningException;
import org.limp.basework.SimpleBean;
import org.limp.basework.SimpleBean4Table;
import org.limp.basework.SimpleBeanMachining;
import org.limp.basework.Table;
import org.limp.basework.impl.CommonBean4HSQ;
import org.limp.basework.impl.SimpleBean4TableImpl;
import org.limp.basework.tools.BaseworkUtil;

import org.limp.mine.DataTrimmerI;
import org.limp.mine.DateTrimmer;
import org.limp.mine.StringTool;
import org.limp.mine.annex.AnnexException;

import com.bk.cyxf.log.LogManager;

import java.io.UnsupportedEncodingException;
import java.sql.Connection;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * 来访对象处理插件类
 * 
 * @author lvt
 * 
 */
public class LfObjectHandler implements SimpleBeanMachining {
	public SimpleBean machining(SimpleBean bean, Table table,
			HttpServletRequest request, Connection conn, int type)
			throws MachiningException {
		// TODO Auto-generated method stub
		if (type == 0) {
			CommonBean4HSQ cbh = (CommonBean4HSQ) bean.getResource().get("CBH");
			IObject obj = (IObject) bean.getResource().get("OBJECT");

			Table tbl = obj.iobject().itable("APP_LF");

			if (tbl == null) {
				throw new MachiningException(
						"LfObjectHandler exception for save object, table 'APP_LF' is null.");
			}

			Map info = (Map) ((List) obj.icontent(tbl)).get(0);

			/* 来访类型 */
			String LFTYPE = StringTool.checkString(info.get("LFTYPE"));

			String lfid = StringTool.checkString(info.get("LFID"));

			RoleManager rm = new RoleManager(conn);

			IRole role = null;

			if (LFTYPE.equals("0")) {
				/* 街乡来信由街乡信访办人员统一办理 */
				role = rm.getRoleByKey("jxxfbuser");
			} else if (LFTYPE.equals("1")) {
				/* 区来信由街乡信访办人员统一办理 */
				role = rm.getRoleByKey("quxfbuser");
			}

			/* 信访系统管理员 */
			IRole xfManager = rm.getRoleByKey("xfmanager");

			IUser user = ISystem.getSessionUser(request);

			PurviewManager pm = new PurviewManager(conn);

			try {
				/* 对信访办角色进行授权,可以对该来访进行办理 */
				pm.insert(obj.id(), obj.iname(), obj.ikey(), "ISYS_OBJECT", 3,
						role.id(), role.iname(), "role", user, false);

				/* 对信访系统管理员角色进行授权,可以对来信进行编辑\删除\查阅 */
				pm.insert(obj.id(), obj.iname(), obj.ikey(), "ISYS_OBJECT", 3,
						xfManager.id(), xfManager.iname(), "role", user, false);
			} catch (Exception ex) {
				throw new MachiningException("purview for object error.", ex);
			}

			try {
				LogManager lm = new LogManager(conn);
				lm.log(user, lfid, "1", "lfdj", "");
			} catch (Exception ex) {
				throw new MachiningException("log lfdj error.", ex);
			}

//			BaseworkUtil util = new BaseworkUtil();

			ObjectManager om = new ObjectManager(conn);

//			try {
//				Map xfblInfo = (Map) ((List) obj.icontent(obj.iobject().itable(
//						"APP_XFHANDLER"))).get(0);
//
//				SimpleBean4Table sbt = new SimpleBean4TableImpl("APP_XFHANDLER");
//				sbt.reload(xfblInfo);
//
//				util.manualDelete1(sbt, conn);
//
//				om.removeSystemRelationObject(obj.id(), obj.iobject().itable(
//						"APP_XFHANDLER"));
//			} catch (Exception ex) {
//				throw new MachiningException("remove lfbl-empty-info error.",
//						ex);
//			}
//
//			try {
//				Map xffcInfo = (Map) ((List) obj.icontent(obj.iobject().itable(
//						"APP_XFFC"))).get(0);
//
//				SimpleBean4Table sbt = new SimpleBean4TableImpl("APP_XFFC");
//				sbt.reload(xffcInfo);
//
//				util.manualDelete1(sbt, conn);
//
//				om.removeSystemRelationObject(obj.id(), obj.iobject().itable(
//						"APP_XFFC"));
//			} catch (Exception ex) {
//				throw new MachiningException("remove lffc-empty-info error.",
//						ex);
//			}
//
//			try {
//				Map xffhInfo = (Map) ((List) obj.icontent(obj.iobject().itable(
//						"APP_XFFH"))).get(0);
//
//				SimpleBean4Table sbt = new SimpleBean4TableImpl("APP_XFFH");
//				sbt.reload(xffhInfo);
//
//				util.manualDelete1(sbt, conn);
//
//				om.removeSystemRelationObject(obj.id(), obj.iobject().itable(
//						"APP_XFFH"));
//			} catch (Exception ex) {
//				throw new MachiningException("remove lffh-empty-info error.",
//						ex);
//			}

			// 处理派遣操作
			deal(request,obj, conn, om, cbh);

		}

		return null;
	}

	/**
	 * 科室派遣
	 * 
	 * @param request
	 * @param conn
	 */
	private void deal(HttpServletRequest request,IObject object, Connection conn,
			ObjectManager manager,CommonBean4HSQ cbh) {

		Table tbl = object.iobject().itable("APP_LF");

		Map info = (Map) ((List) object.icontent(tbl)).get(0);
		
		String id = StringTool.checkString(object.id());
		String lfid = StringTool.checkString(info.get("LFID"));

		String status = StringTool.checkString(info.get("BLSTATUS"));

		try {

				IUser user = ISystem.getSessionUser(request);

				if (manager.purview(id, user) < 2) {
					request.setAttribute("result",
							"{success: false, errCode : '-2'}");
				} else {
					

					/* 来访类型 */
					String LFTYPE = StringTool.checkString(info.get("LFTYPE"));

					/* 自处理 */
					String stsLabel = "自处理";

					if (status.equals("2")) {
						/* 办理 */
						stsLabel = "派遣办理";
					} else if (status.equals("3")) {
						/* 上报 */
						stsLabel = "上报处理";
					} else if (status.equals("-1")) {
						/* 不予办理 */
						stsLabel = "不予办理";
					}

					//CommonBean4HSQ cbh = new CommonBean4HSQ(request);

					SimpleBean4Table sbt = new SimpleBean4TableImpl("APP_LF",
							cbh);

					sbt.getResource().put("lfid", lfid);

					sbt.getResource().put("PQRID", user.id());
					sbt.getResource().put("PQRNAME", user.iname());
					sbt.getResource().put("PQRGROUPID", user.igroup().id());
					sbt.getResource()
							.put("PQRGROUPNAME", user.igroup().iname());

					if (status.equals("-1") || status.equals("1")) {
						sbt.getResource().put("LFSTATUS", "1");

						String backInfo = StringTool.checkString(request
								.getParameter("H_BACKINFO"));

						/* 信访办办理 */
						SimpleBean4Table sbt1 = new SimpleBean4TableImpl(
								"APP_XFHANDLER");
						sbt1.getResource().put("H_GROUPID", user.igroup().id());
						sbt1.getResource().put("H_GROUPNAME",
								user.igroup().iname());
						sbt1.getResource().put("XFID", lfid);
						sbt1.getResource().put("XF_TYPE", "1");
						sbt1.getResource().put("H_USERID", user.id());
						sbt1.getResource().put("H_USERNAME", user.iname());
						sbt1.getResource().put("H_STATUS", "1");
						sbt1.getResource().put("H_BACKINFO", backInfo);
						sbt1.getResource().put("H_DATE",
								DateTrimmer.getYMDHMS());

						BaseworkUtil util = new BaseworkUtil();
						Map m = util.manualSave1(sbt1, conn);

						manager.createSystemRelationObject(lfid, "APP_XFHANDLER",
								(String) m.get("HID"));
					} else if (status.equals("2")) {
						
						String jbrgroupid = StringTool.checkString(cbh.getResource().get("H_GROUPID"));
						jbrgroupid += "," +user.igroup().id();
						String jbrgroupname = StringTool.checkString(cbh.getResource().get("H_GROUPNAME"));
						jbrgroupname += "," +user.igroup().iname();
						String[] idArray = jbrgroupid.split(",");
						String[] nameArray = jbrgroupname.split(",");
						
						String SSDNAMEFULLNAME = StringTool.checkString(info.get("SSDNAME"));
			            
			            int idx = SSDNAMEFULLNAME.indexOf("-");
			            int idx2 = SSDNAMEFULLNAME.lastIndexOf(">");
			            String SSDNAME = SSDNAMEFULLNAME.substring(0, idx);
			            String prix = "";
			            //具体社区名
			            String sq = SSDNAMEFULLNAME.substring(idx2+1);
			            if (LFTYPE.equals("0")) {
			                /*街乡*/
			            	prix = "街乡/"+SSDNAME + "/";
			            } else if (LFTYPE.equals("1")) {
			                /*区*/
			            	prix = "朝阳区政府/"+SSDNAME + "/";
			            }

						BaseworkUtil util = new BaseworkUtil();
						PurviewManager pm = new PurviewManager(conn);
						RoleManager rm = new RoleManager(conn);

						for (int i = 0; i < nameArray.length; i++) {

							/* 派遣科室办理 */
							SimpleBean4Table sbt1 = new SimpleBean4TableImpl(
									"APP_XFHANDLER");
							
							if("社区/行政村".equals(nameArray[i])){
								List<Map> groupList = searchMultiDept(conn,prix+sq);
								for(Map m : groupList){
									/* 添加处理科室ID */
									sbt1.getResource().put("H_GROUPID", m.get("ID"));

									/* 添加处理科室名称 */
									sbt1.getResource().put("H_GROUPNAME", m.get("NAME"));

									sbt1.getResource().put("XFID", lfid);
									sbt1.getResource().put("XF_TYPE", "1");
									sbt1.getResource().put("H_STATUS", "0");

									Map rsm = util.manualSave1(sbt1, conn);

									manager.createSystemRelationObject(id,
											"APP_XFHANDLER", (String) rsm.get("HID"));
									
								}
							}else{
								Map<String,String> groupMap = searchSingleDept(conn,prix+nameArray[i]);
								if(groupMap != null){
									
									/* 添加处理科室ID */
									sbt1.getResource().put("H_GROUPID", groupMap.get("ID"));

									/* 添加处理科室名称 */
									sbt1.getResource().put("H_GROUPNAME", groupMap.get("NAME"));

									sbt1.getResource().put("XFID", lfid);
									sbt1.getResource().put("XF_TYPE", "1");
									sbt1.getResource().put("H_STATUS", "0");

									Map rsm = util.manualSave1(sbt1, conn);

									manager.createSystemRelationObject(id,
											"APP_XFHANDLER", (String) rsm.get("HID"));
									
								}
								
							}

							

						}

						IRole role = null;

						/* 街乡信访办理负责人 */
						if (LFTYPE.equals("0")) {
							role = rm.getRoleByKey("jxpic");
						}
						/* 区信访办理负责人 */
						else if (LFTYPE.equals("1")) {
							role = rm.getRoleByKey("qupic");
						}

						/* 授权信访办理负责人可对来信进行办理 */
						pm.insert(object.id(), object.iname(), object.ikey(),
								"ISYS_OBJECT", 3, role.id(), role.iname(),
								"role", user, false);
					}

					BaseworkUtil util = new BaseworkUtil();

					util.manualUpdate1(sbt, conn);

					LogManager lm = new LogManager(conn);

					lm.log(user, lfid, "1", "lfcz", stsLabel);

					/* 上报 */
					if (status.equals("3")) {
					}

					request.setAttribute("result", "{success: true}");

				}
			
		} catch (Exception ex) {
			request.setAttribute("result", "{success: false, errCode : '-3'}");
			ISystem.catchException(request, this, ex);
		}

	}
	

    /**
     * 查找部门表中的部门
     * @param conn
     * @param flumenames
     */
    private Map<String,String> searchSingleDept(Connection conn,String flumenames){
    	
    	String sql = "SELECT * FROM ISYS_DEPARTMENT WHERE FLUMENAMES = ?";

        DataTrimmerI trimmer = new DataTrimmerI(conn);

        DataTrimmerI.DataItemList dil = trimmer.createDIL();

        dil.set(flumenames);

        Map<String,String> hdlMap = trimmer.searchSingleData(sql, dil);
        
        return hdlMap;
    	
    }
    
    /**
     * 查询社区/行政村
     * @param conn
     * @param flumenames
     * @return
     */
    private List<Map> searchMultiDept(Connection conn,String flumenames){
    	
    	String sql = "SELECT * FROM ISYS_DEPARTMENT WHERE FLUMENAMES = ?";

        DataTrimmerI trimmer = new DataTrimmerI(conn);

        DataTrimmerI.DataItemList dil = trimmer.createDIL();

        dil.set(flumenames);

        List<Map>  resultList= trimmer.searchMultiData(sql, dil);
        
        return resultList;
    	
    }
}
